<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>下载历史 - ZLibLike平台</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/style.css">
    <link rel="stylesheet" href="/css/daterangepicker.css">
</head>
<body>
    <div th:replace="~{commons/header :: header}"></div>
    
    <div class="container mt-4">
        <h2>我的下载历史</h2>
        
        <div class="card mt-3">
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="dateRangePicker">日期范围</label>
                            <input type="text" id="dateRangePicker" class="form-control" />
                        </div>
                    </div>
                    <div class="col-md-2 align-self-end">
                        <button id="searchBtn" class="btn btn-primary">
                            <i class="fa fa-search"></i> 查询
                        </button>
                    </div>
                    <div class="col-md-2 offset-md-4 align-self-end">
                        <button id="batchDeleteBtn" class="btn btn-danger" disabled>
                            <i class="fa fa-trash"></i> 批量删除
                        </button>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead class="thead-dark">
                            <tr>
                                <th>
                                    <input type="checkbox" id="selectAll" />
                                </th>
                                <th>书名</th>
                                <th>下载格式</th>
                                <th>文件大小</th>
                                <th>下载时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="downloadHistory">
                            <!-- 下载历史将动态加载 -->
                        </tbody>
                    </table>
                </div>
                
                <div id="pagination" class="d-flex justify-content-center mt-3">
                    <!-- 分页组件将动态加载 -->
                </div>
                
                <div id="emptyHistory" class="text-center p-5 d-none">
                    <h4>暂无下载记录</h4>
                    <p>您可以在书籍页面下载感兴趣的电子书</p>
                    <a href="/books" class="btn btn-primary mt-2">浏览书籍</a>
                </div>
            </div>
        </div>
    </div>
    
    <div th:replace="~{commons/footer :: footer}"></div>
    
    <script src="/js/jquery-3.6.0.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/moment.min.js"></script>
    <script src="/js/daterangepicker.js"></script>
    <script th:inline="javascript">
        $(document).ready(function() {
            let startDate = null;
            let endDate = null;
            let currentPage = 1;
            const pageSize = 10;
            let selectedDownloads = [];
            
            // 初始化日期范围选择器
            $('#dateRangePicker').daterangepicker({
                autoUpdateInput: false,
                locale: {
                    cancelLabel: '清除',
                    applyLabel: '确定',
                    format: 'YYYY-MM-DD'
                }
            });
            
            $('#dateRangePicker').on('apply.daterangepicker', function(ev, picker) {
                $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
                startDate = picker.startDate.format('YYYY-MM-DD');
                endDate = picker.endDate.format('YYYY-MM-DD');
            });
            
            $('#dateRangePicker').on('cancel.daterangepicker', function(ev, picker) {
                $(this).val('');
                startDate = null;
                endDate = null;
            });
            
            // 加载下载历史
            function loadDownloadHistory(page = 1) {
                currentPage = page;
                let url = `/api/book/downloads?page=${page}&size=${pageSize}`;
                
                if (startDate) {
                    url += `&startDate=${startDate}`;
                }
                
                if (endDate) {
                    url += `&endDate=${endDate}`;
                }
                
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            const pageResult = data.data;
                            
                            if (pageResult.records.length === 0) {
                                $('#emptyHistory').removeClass('d-none');
                                $('#downloadHistory').html('');
                                $('#pagination').html('');
                                return;
                            }
                            
                            $('#emptyHistory').addClass('d-none');
                            
                            // 渲染数据
                            renderDownloadHistory(pageResult.records);
                            
                            // 渲染分页
                            renderPagination(pageResult.currentPage, pageResult.totalPages);
                        } else {
                            alert(data.message);
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }
            
            // 渲染下载历史列表
            function renderDownloadHistory(records) {
                let html = '';
                
                records.forEach(record => {
                    const downloadTime = new Date(record.downloadTime).toLocaleString();
                    const fileSize = record.fileSize ? record.fileSize.toFixed(2) + ' MB' : '-';
                    
                    html += `
                        <tr>
                            <td>
                                <input type="checkbox" class="download-checkbox" value="${record.downloadId}" />
                            </td>
                            <td>${record.title}</td>
                            <td>${record.format}</td>
                            <td>${fileSize}</td>
                            <td>${downloadTime}</td>
                            <td>
                                <button class="btn btn-sm btn-danger delete-btn" data-id="${record.downloadId}">
                                    <i class="fa fa-trash"></i> 删除
                                </button>
                            </td>
                        </tr>
                    `;
                });
                
                $('#downloadHistory').html(html);
                
                // 绑定事件
                $('.delete-btn').click(function() {
                    const downloadId = $(this).data('id');
                    deleteDownloadHistory(downloadId);
                });
                
                // 复选框事件
                $('.download-checkbox').change(function() {
                    updateSelectedDownloads();
                });
                
                // 全选/取消全选
                $('#selectAll').change(function() {
                    $('.download-checkbox').prop('checked', $(this).prop('checked'));
                    updateSelectedDownloads();
                });
            }
            
            // 渲染分页
            function renderPagination(currentPage, totalPages) {
                if (totalPages <= 1) {
                    $('#pagination').html('');
                    return;
                }
                
                let html = '<nav><ul class="pagination">';
                
                // 上一页
                if (currentPage > 1) {
                    html += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a></li>`;
                } else {
                    html += '<li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>';
                }
                
                // 页码
                const startPage = Math.max(1, currentPage - 2);
                const endPage = Math.min(totalPages, startPage + 4);
                
                for (let i = startPage; i <= endPage; i++) {
                    if (i === currentPage) {
                        html += `<li class="page-item active"><a class="page-link" href="#">${i}</a></li>`;
                    } else {
                        html += `<li class="page-item"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
                    }
                }
                
                // 下一页
                if (currentPage < totalPages) {
                    html += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a></li>`;
                } else {
                    html += '<li class="page-item disabled"><a class="page-link" href="#">下一页</a></li>';
                }
                
                html += '</ul></nav>';
                
                $('#pagination').html(html);
                
                // 绑定事件
                $('.page-link').click(function(e) {
                    e.preventDefault();
                    const page = $(this).data('page');
                    if (page) {
                        loadDownloadHistory(page);
                    }
                });
            }
            
            // 更新已选择的下载记录
            function updateSelectedDownloads() {
                selectedDownloads = [];
                $('.download-checkbox:checked').each(function() {
                    selectedDownloads.push($(this).val());
                });
                
                // 启用/禁用批量删除按钮
                $('#batchDeleteBtn').prop('disabled', selectedDownloads.length === 0);
            }
            
            // 删除单条下载记录
            function deleteDownloadHistory(downloadId) {
                if (!confirm('确定删除此下载记录吗？')) {
                    return;
                }
                
                fetch(`/api/book/downloads/${downloadId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        alert('删除成功');
                        loadDownloadHistory(currentPage);
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败');
                });
            }
            
            // 批量删除下载记录
            function batchDeleteDownloadHistory() {
                if (selectedDownloads.length === 0) {
                    return;
                }
                
                if (!confirm(`确定删除选中的 ${selectedDownloads.length} 条记录吗？`)) {
                    return;
                }
                
                fetch('/api/book/downloads/batch', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(selectedDownloads)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        alert(`成功删除 ${data.data} 条记录`);
                        loadDownloadHistory(currentPage);
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('批量删除失败');
                });
            }
            
            // 绑定事件
            $('#searchBtn').click(function() {
                loadDownloadHistory(1);
            });
            
            $('#batchDeleteBtn').click(function() {
                batchDeleteDownloadHistory();
            });
            
            // 加载初始数据
            loadDownloadHistory();
        });
    </script>
</body>
</html> 